package com.xinghen.common.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xinghen
 * @ClassName: ThreadContextHolder
 * @Package: com.xinghen.common.util
 * @Description 线程本地变量Map
 * @create 2018/4/18 16:11
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ThreadContextHolder {

    private static final ThreadLocal<Map<String, Object>> HOLDER = new MapThreadLocal();

    public static void put(String key, Object value) {
        getContextMap().put(key, value);
    }

    public static Object get(String key) {
        return getContextMap().get(key);
    }

    public static void remove(String key) {
        getContextMap().remove(key);
    }

    public static void clear() {
        getContextMap().clear();
    }

    public static Map<String, Object> getContextMap() {
        return HOLDER.get();
    }

    private static class MapThreadLocal extends ThreadLocal<Map<String, Object>> {

        @Override
        protected Map<String, Object> initialValue() {
            return new HashMap<String, Object>(8) {
                @Override
                public Object put(String key, Object value) {
                    return super.put(key, value);
                }
            };
        }

    }

}
